package com.afs.electronicforensics.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentManager;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.NavigationUI;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;

import android.widget.TextView;
import android.widget.Toast;

import com.afs.electronicforensics.config.MyOSSconfig;
import com.afs.electronicforensics.entity.Result;
import com.afs.electronicforensics.utils.Constants;
import com.afs.electronicforensics.utils.CreateDialog;
import com.afs.electronicforensics.utils.MediaUtil;
import com.afs.electronicforensics.utils.OssManager;
import com.afs.electronicforensics.utils.RecordUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;


import androidx.appcompat.widget.Toolbar;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLOutput;

import de.hdodenhof.circleimageview.CircleImageView;

import static com.afs.electronicforensics.utils.Constants.USER_ROOT;

public class ShowActivity extends AppCompatActivity {

    private boolean mIsExit;
    private DrawerLayout drawerLayout;
    private BottomNavigationView bottomNavigationView;
    private TextView username;

    private CircleImageView toolbarAvatar;
    private CircleImageView avatar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        System.out.println(USER_ROOT.getUid());

        toolbarAvatar = findViewById(R.id.toolbarImage);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS},1);
        }


        initView();


        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        drawerLayout = findViewById(R.id.drawer_layout);

        NavigationView navigationView= findViewById(R.id.navigation_view);
        toolbarAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });
        View headerView = navigationView.getHeaderView(0);
        avatar = headerView.findViewById(R.id.avatar);

        if(USER_ROOT.getUserAvatar() != null){
            String url = MyOSSconfig.FILE_URL + USER_ROOT.getUserAvatar();
            Glide.with(ShowActivity.this).load(url).into(toolbarAvatar);
            Glide.with(ShowActivity.this).load(url).into(avatar);
        }else{
            Glide.with(ShowActivity.this).load(R.drawable.avatar_default).into(toolbarAvatar);
            Glide.with(ShowActivity.this).load(R.drawable.avatar_default).into(avatar);
        }

        username = headerView.findViewById(R.id.username);
        username.setText(USER_ROOT.getUsername());
        avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CreateDialog.createAvatarDialog(ShowActivity.this);
            }
        });
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.nav_info:
                        drawerLayout.closeDrawers();
                        break;
                    case R.id.nav_exit:
                        drawerLayout.closeDrawers();
                        Intent intent = new Intent();
                        intent.setClass(ShowActivity.this, LoginActivity.class);
                        USER_ROOT.destroy();

                        SharedPreferences sp = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("userCode",null);
                        editor.putString("password",null);
                        editor.putBoolean("autoLogin", false);
                        editor.commit();

                        startActivity(intent);
                        ShowActivity.this.finish();
                        break;
                    default:
                        break;
                }
                return true;
            }
        });



    }

    public boolean onMenuOpened(int featureId,Menu menu) {
        if (menu != null) {
            if (menu.getClass().getSimpleName().equalsIgnoreCase("MenuBuilder")) {
                try {
                    Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible",Boolean.TYPE);
                    method.setAccessible(true);
                    method.invoke(menu,true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return super.onMenuOpened(featureId,menu);
    }
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.toolbar_menu,menu);

        return true;

    }

    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()){
            case android.R.id.home:
                drawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.photo:
                MediaUtil.openCameraForImage(this);
                MediaUtil.imageFlag = true;
                break;
            case R.id.video:
                MediaUtil.openCameraForVideo(this);
                break;
            case R.id.record:
                MediaUtil.openAudioRecordForAudio(this);
                break;
            case R.id.system:
                CreateDialog.createChoiceDialog(this);
                break;
        }
        return true;
    }



    //返回结果
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //当结果码为RESULT_OK时,表示用户有效
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            //打开设备部分
            case Constants.FLAG_REQUEST_CAMERA_IMAGE:
                if (resultCode == RESULT_OK) {
                    MediaUtil.cropPhoto(MediaUtil.URI,this,MediaUtil.imageFlag);//裁剪图片
                }
                break;
            case Constants.FLAG_REQUEST_CAMERA_VIDEO:
                if (resultCode == RESULT_OK) {
                   MediaUtil.cropVideo(this,MediaUtil.PATH);//裁剪视频
                }
                break;
            case Constants.FLAG_REQUEST_RECORD_AUDIO:
                if (resultCode == RESULT_OK) {
                    MediaUtil.cropAudio(this, RecordUtils.PATH);//裁剪音频
                }
                break;


            //选取部分
            case Constants.FLAG_REQUEST_SYSTEM_IMAGE:
                if (resultCode == RESULT_OK) {
                    String imagePath = MediaUtil.getImagePathFromSystem(this, data);
                    System.out.println(imagePath);
                    MediaUtil.cropPhoto(data.getData(),this,MediaUtil.imageFlag);//裁剪图片
                }
                break;
            case Constants.FLAG_REQUEST_SYSTEM_VIDEO:
                if (resultCode == RESULT_OK) {
                    String videoPath = MediaUtil.getVideoPathFromSystem(this, data);
                    System.out.println(videoPath);
                    MediaUtil.cropVideo(this,videoPath);//裁剪视频
                }
                break;
            case Constants.FLAG_REQUEST_SYSTEM_AUDIO:
                if (resultCode == RESULT_OK) {
                    String audioPath = MediaUtil.getAudioPathFromSystem(this, data);
                    System.out.println(audioPath);
                    MediaUtil.cropAudio(this,audioPath);//裁剪音频
                }
                break;


            //裁剪部分
            case Constants.FLAG_REQUEST_CROP_IMAGE:
                if (resultCode == RESULT_OK) {
                    /*Intent intent=new Intent(this, this.getClass());
                    startActivity(intent);*/
                    if(MediaUtil.imageFlag){
                        Toast.makeText(ShowActivity.this, "保存成功！", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent();
                        intent.setClass(this, ShowActivity.class);
                        startActivity(intent);
                        this.finish();
                    }else {
                        String avatarPath = MediaUtil.PATH;
                        OssManager.getInstance().init(getApplicationContext()).uploadHead(avatarPath.substring(avatarPath.indexOf(".")),avatarPath, USER_ROOT.getUsername());
                        Glide.with(ShowActivity.this).load(avatarPath).into(toolbarAvatar);
                        Glide.with(ShowActivity.this).load(avatarPath).into(avatar);
                    }

                }
                break;
            case Constants.FLAG_REQUEST_CROP_VIDEO:
                if (resultCode == RESULT_OK) {
                    Toast.makeText(ShowActivity.this, "保存成功！", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent();
                    intent.setClass(this, ShowActivity.class);
                    startActivity(intent);
                    this.finish();
                }
                break;
            case Constants.FLAG_REQUEST_CROP_AUDIO:
                if (resultCode == RESULT_OK) {
                    Toast.makeText(ShowActivity.this, "保存成功！", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent();
                    intent.setClass(this, ShowActivity.class);
                    startActivity(intent);
                    this.finish();
                }
                break;
            default:
                break;
        }
    }

    private void initView(){
        bottomNavigationView=findViewById(R.id.bottom_navigation);

        FragmentManager fragmentManager=getSupportFragmentManager();
        NavHostFragment navHostFragment=(NavHostFragment) fragmentManager.findFragmentById(R.id.nav_fragment);
        NavController navController=navHostFragment.getNavController();
        NavigationUI.setupWithNavController(bottomNavigationView,navController);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                if(item.getItemId()==R.id.bottom_nav_album)
                {
                    if(item.isChecked()){
                        return true;
                    }
                    item.setChecked(true);
                    navController.navigate(R.id.nav_exit);
                }else if (item.getItemId()==R.id.bottom_nav_video){
                    if(item.isChecked()){
                        return true;
                    }
                    item.setChecked(true);
                    navController.navigate(R.id.nav_video);
                }else if (item.getItemId()==R.id.bottom_nav_record){
                    if(item.isChecked()){
                        return true;
                    }
                    item.setChecked(true);
                    navController.navigate(R.id.nav_record);
                }
                return false;
            }
        });

    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mIsExit) {
                this.finish();
            } else {
                Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
                mIsExit = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mIsExit = false;
                    }
                }, 2000);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}